/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxSum = INT_MIN;
    int _maxPathSum(TreeNode* root) {
        if (root == nullptr) return 0;

        int left = _maxPathSum(root->left);
        if (left < 0) left = 0;
        int right = _maxPathSum(root->right);
        if (right < 0) right = 0;

        maxSum = max(maxSum, left + right + root->val);
        int result = max(left, right) + root->val;
        return result > 0 ? result : 0;
    }

    int maxPathSum(TreeNode* root) {
        _maxPathSum(root);
        return maxSum;
    }
};
